package start;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Merge {
	FileWriter target;
	PrintWriter out;
	
	FileInputStream source;
	
	InputStreamReader in;

	String filename;
	int block_nr;
	String directory = "./files";

	ArrayList<File> files = new ArrayList<File>();

	public static void main(String args[]) {
		new Merge("text.txt", 1);
	}
	

	public Merge(String filename, int block_nr) {
		this.filename = filename;
		this.block_nr = block_nr;
	}
	
	
	public String merge() {
		File dir = new File(directory);

		File[] array = dir.listFiles();
		Arrays.sort(array);

		for (File f : array) {
			if (f.getName().matches(filename + ".block\\d+")) {
				
				if ( Integer.parseInt(f.getName().split("block")[1]) >= block_nr ) {
					files.add(f);
				}
			}
		}

		String line = "";
		
		for (File f : files) {
			try {
				source 	= new FileInputStream(f);
				line += convertStreamToString(source);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
		
		}
		
		return line;
		
		/*try {
			target = new FileWriter("./files/" + filename);
			out = new PrintWriter(target);

			for (File f : files) {
				source 	= new FileInputStream(f);
				
				String line = convertStreamToString(source);
				
				out.write(line);
			}
			
			out.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}
	
	public String convertStreamToString(InputStream is) { 
	    return new Scanner(is).useDelimiter("\\A").next();
	}
}
